import Mock from 'mockjs'

// 模拟用户数据
const users = [
  {
    id: 1,
    username: 'admin',
    password: '123456',
    email: 'admin@example.com',
    avatar: 'https://avatars.githubusercontent.com/u/1?v=4',
    role: 'admin'
  }
]

// 登录接口
Mock.mock('/api/login', 'post', (options: any) => {
  const { username, password } = JSON.parse(options.body)
  const user = users.find(u => u.username === username && u.password === password)

  if (user) {
    return {
      code: 200,
      data: {
        token: Mock.Random.guid(),
        user: {
          id: user.id,
          username: user.username,
          email: user.email,
          avatar: user.avatar,
          role: user.role
        }
      },
      message: '登录成功'
    }
  }
  return {
    code: 401,
    message: '用户名或密码错误'
  }
})

// 注册接口
Mock.mock('/api/register', 'post', (options: any) => {
  const { username, password, email } = JSON.parse(options.body)

  if (users.some(u => u.username === username)) {
    return {
      code: 400,
      message: '用户名已存在'
    }
  }

  const newUser = {
    id: users.length + 1,
    username,
    password,
    email,
    avatar: `https://avatars.githubusercontent.com/u/${users.length + 1}?v=4`,
    role: 'user'
  }

  users.push(newUser)

  return {
    code: 200,
    data: {
      id: newUser.id,
      username: newUser.username,
      email: newUser.email,
      avatar: newUser.avatar,
      role: newUser.role
    },
    message: '注册成功'
  }
})

// 获取用户信息接口
Mock.mock(/\/api\/user\/\d+/, 'get', (options: any) => {
  const id = parseInt(options.url.match(/\/api\/user\/(\d+)/)[1])
  const user = users.find(u => u.id === id)

  if (user) {
    return {
      code: 200,
      data: {
        id: user.id,
        username: user.username,
        email: user.email,
        avatar: user.avatar,
        role: user.role
      }
    }
  }
  return {
    code: 404,
    message: '用户不存在'
  }
}) 